package com.liesheng.haylou.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.util.Log;


import com.liesheng.daemonlib.LogUtil;
import com.liesheng.haylou.app.HyApplication;
import com.liesheng.haylou.service.TraceServiceImpl;
import com.liesheng.haylou.ui.main.DialogActivity;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Date:2019/11/18
 * <p>
 * Author:wuzhiguang
 * <p>
 * Description:
 * ble操作类
 */
public class BleUtil {

    private BluetoothAdapter bluetoothAdapter;


    public BleUtil() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
            LogUtil.d("BleUtil  --- onLeScan");
        }

    };

    public boolean isBluetoothOpen(){
        return bluetoothAdapter!=null && bluetoothAdapter.isEnabled();
    }

    // 扫描BLE蓝牙(不会扫描经典蓝牙)
    // 应用退到后台,要想能够扫描蓝牙,一定要打开位置信息开关
    public void scanBle(final BluetoothAdapter.LeScanCallback scanCallback) {
        bluetoothAdapter.startLeScan(scanCallback == null ? leScanCallback : scanCallback);
    }

    public void stopScan(BluetoothAdapter.LeScanCallback scanCallback) {
        bluetoothAdapter.stopLeScan(scanCallback == null ? leScanCallback : scanCallback);
    }

    //连接ble
    public BluetoothGatt connect(BluetoothDevice device, BluetoothGattCallback gattCallback) {
        BluetoothGatt gatt = device.connectGatt(HyApplication.mApp, false, gattCallback);
        return gatt;
    }

    //关闭连接
    public void closeConn(BluetoothGatt gatt) {
        if (gatt != null) {
            gatt.disconnect();
            gatt.close();
            gatt = null;
        }
    }

}
